<?php

namespace app\home\controller\device;

use app\home\controller\AuthController;
use services\{UtilService as Util, JsonService as Json};
use app\home\model\store\{StoreDevice, DeviceCategory};
use app\home\model\system\SystemStore;
use services\FormBuilder as Form;
use think\facade\Route as Url;

/**
 * 设备分类控制器
 * Class Category
 * @package app\home\controller\device
 */
class Category extends AuthController
{
    /**
     * 分类的首页
     */
    public function index()
    {
        // 获取所有的分类
        $where = Util::getMore([
            ["cat_name", ""]
        ], $this->request);
        $this->assign("where", $where);
        // 获取分页的数据
        $this->assign(DeviceCategory::systemPage($where));
        return $this->fetch();
    }

    /**
     * 新增页面
     * @return string
     */
    public function create()
    {
        $f = [];
        $f[] = Form::input("cat_name", "设备的名称");
        $f[] = Form::number("sort", "排序");
        $form = Form::make_post_form("新增分类", $f, Url::buildUrl("save"));
        $this->assign(compact("form"));
        return $this->fetch("public/form-builder");
    }

    /**
     * 新增
     * @param int $id
     * @return false|string
     */
    public function save($id = 0)
    {
        $data = Util::getMore([
            ["cat_name", ''],
            ["sort", 0]
        ]);
        if (!$id) {
            if (DeviceCategory::where("id", $id)->count()) return Json::fail("分类已经存在");
        }
        if (!$data["cat_name"]) return Json::fail("请输入设备名称");
        $data["wxapp_id"] = $this->wxapp_id;
        if ($id) {  // 编辑
            $res = DeviceCategory::edit($data, $id);
            if ($res)
                return Json::successful("修改分类成功");
            return Json::fail("修改分类失败");
        } else {
            $data["add_time"] = time();
            $res = DeviceCategory::create($data);
            if ($res)
                return Json::successful("新增分类成功");
            else
                return Json::fail("新增分类失败，请稍后再试");
        }
    }

    /**
     * 编辑的页面
     * @param $id
     * @return false|string
     */
    public function edit($id)
    {
        $service = DeviceCategory::get($id);
        if (!$service) return Json::fail("分类信息不存在");
        $f = [
            Form::input("cat_name", "设备名称", $service["cat_name"]),
            Form::number("sort", "排序", $service["sort"]),
        ];
        $form = Form::make_post_form("修改分类", $f, Url::buildUrl("save", compact("id")));
        $this->assign(compact("form"));
        return $this->fetch("public/form-builder");
    }

    /**
     * 删除
     * @param $id
     * @return false|string
     */
    public function delete($id)
    {
        $res = DeviceCategory::edit(["is_del" => 1], $id);
        if ($res)
            return Json::successful("删除成功");
        else
            return Json::fail("删除失败");
    }
}